﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

namespace FzWeb.Utility
{
    public class FileUpload
    {
        public static string Upload(HttpPostedFileBase fileToUpload)
        {
            if (fileToUpload != null)
            {
                string path = HttpContext.Current.Server.MapPath("/Content/Upload/");
                DateTime today = DateTime.Today;
                string dirname = string.Format("/Content/Upload/{0}/{1}/", today.Year, today.Month);
                string dir = string.Format("{0}{1}\\{2}", path, today.Year, today.Month);
                Directory.CreateDirectory(dir);
                string ext = Path.GetExtension(fileToUpload.FileName);
                int i = 1;
                string filename;
                string fname;
                do
                {
                    fname = string.Format("{0}{1}", i++, ext);
                    filename = Path.Combine(dir, fname);
                }
                while (System.IO.File.Exists(filename));
                fileToUpload.SaveAs(filename);
                string response = string.Format("{0}{1}", dirname, fname);
                
                return response;
            }
            return null;
        }
    }
}
